package cn.tedu.tmall.front.mall.dao.repository.impl;

import cn.tedu.tmall.common.PageDataVO;
import cn.tedu.tmall.front.mall.dao.mapper.GoodMapper;
import cn.tedu.tmall.front.mall.dao.repository.IGoodRepository;
import cn.tedu.tmall.front.mall.pojo.po.GoodPO;
import cn.tedu.tmall.front.mall.pojo.vo.GoodItemVO;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Repository
public class GoodRepository implements IGoodRepository {
    @Autowired
    private GoodMapper goodMapper;
    @Override
    public PageDataVO<GoodItemVO> listGoodByCategoryId(Long categoryId, Integer pageNum, Integer pageSize) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("category_id",categoryId);
        goodMapper.selectList(queryWrapper);
        //获得原始数据
        PageHelper pageHelper = new PageHelper();
        pageHelper.startPage(pageNum,pageSize);
        List list = goodMapper.selectList(queryWrapper);
        log.debug("list:{}",list);
        PageInfo pageInfo = new PageInfo<>(list);
        log.debug("pageInfo:{}",pageInfo);
        //转换成PageDataVO<GoodItemVO>
        PageDataVO<GoodItemVO> pageDataVO = new PageDataVO<>();
        //list无法直接复制需要
        //pageInfo中的数据为PO需要转化为vo
        //cope
        BeanUtils.copyProperties(pageInfo,pageDataVO);
        List goodPOList2itemVOList = goodPOList2itemVOList(pageInfo.getList());
        pageDataVO.setList(goodPOList2itemVOList);
        log.debug("goodPOList2itemVOList:{}",goodPOList2itemVOList);
        return pageDataVO;
    }
    private List<GoodItemVO> goodPOList2itemVOList(List<GoodPO> goodPOList){
        List<GoodItemVO> goodItemVOS = new ArrayList<>();
        for (GoodPO goodPO : goodPOList) {
            GoodItemVO goodItemVO = new GoodItemVO();
            BeanUtils.copyProperties(goodPO,goodItemVO);
            goodItemVOS.add(goodItemVO);
        }
        return goodItemVOS;
    }
 }
